import 'dart:async';

import 'package:get/get.dart';
import 'package:xindong/common/xindong_methods.dart';
import 'package:xindong/routes/call/controller/xindong_call_controller.dart';
import 'package:xindong/routes/call/controller/xindong_call_handle.dart';
import 'package:xindong/utils/xindong_calender_util.dart';

class XinDongCallTimerController extends GetxController {
  static XinDongCallTimerController get to => Get.find();

  // 余额不足
  bool balanceNotEnough = false;

  // 计时定时器（让用户知道通话时长）
  Timer? _countTimer;

  // 当前服务时间戳(XinDongCallProvider.instance.resultClass.sysCurrentTime)
  // 开始通话的时间戳(毫秒，用于计算通话时长)
  // int startTimestamp = 0;
  int countSeconds = 0;

  // 时间相关
  // 用于显示的时间文本
  String showCallTime = "--:--";

  // 余额不足
  int checkBalanceTime = -1;
  String showBalanceTime = "00:00";

  // 创建定时器
  void createTimer() {
    // 余额不足
    balanceNotEnough = false;
    showCallTime = "00:00";
    update();
    _countTimer?.cancel();
    _countTimer = null;
    _countTimer = Timer.periodic(const Duration(seconds: 1), (timer) async {
      countSeconds++;
      checkBalanceTime--;
      try {
        // 小数部分取整
        showCallTime = XinDongCalendarUtil.timeTextHMS(countSeconds);
        showBalanceTime = XinDongCalendarUtil.timeTextHMS(checkBalanceTime);
        // 外部需要使用定时器
        // chatProvider.timerAction();
        update();
      } catch (error) {
        mCatchPrint(error);
      } finally {
        if (XinDongCallController.to.timer_switch == 1 && XinDongCallController.to.isMineInvite && countSeconds % 60 == 0) {
          final result = await XinDongCallHandle().xindong_checkTimeThanStop(countSeconds);
          if (result) {
            XinDongCallController.to.hangup();
          }
        }

        // 扣费端
        // if (XinDongCallController.to.isConsumer && checkTime >= 10) {
        //   final result = await XinDongCallHandle().xindong_checkBalance(times: countSeconds);
        //   if (result) {
        //     checkTime = 0;
        //   }
        // }
        // if (XinDongCallController.to.serverClass.roomId != null && XinDongCallController.to.serverClass.roomId != 0) {
        //   if (XinDongCallController.to.serverClass.sysCurrentTime >=
        //       XinDongCallController.to.serverClass.nextChargeTime!) {
        // 扣费端发起扣费请求
        // if (XinDongCallController.to.isConsumer) {
        // 定时扣费，不扣费系统将强制结束
        // XinDongCallServerClass? resultClass = await _callingHandle.taoke_consume();
        // if (resultClass != null) {
        //   XinDongCallController.to.serverClass.nextChargeTime = resultClass.nextChargeTime;
        // }
        // }
        // consumeException(XinDongCallProvider.instance.isConsumer);
        // } else {
        // chatProvider.addConsumerToMessageList(XinDongGroupTextMessage()
        //   ..type = XinDongGroupMessageType.consumeSuccessful
        //   ..text = "温馨提示：\n对方扣费成功，通话收益不受影响。");
        //   }
        // }
      }
    });
  }

  // 销毁定时器
  void destroyTimer() {
    _countTimer?.cancel();
    _countTimer = null;
    showCallTime = "--:--";
    showBalanceTime = "00:00";
    balanceNotEnough = false;
    checkBalanceTime = -1;
  }

  // 计算时间差（毫秒）
  //
  // return 当前时间戳-开始的时间戳
  int countTimeDifference() {
    return countSeconds * 1000;
    // 通话时间，用于显示，不用来计费（毫秒）time stamp
    // return DateTime.now().millisecondsSinceEpoch - startTimestamp;
  }

  // 显示余额提醒
  void showBalanceView(int seconds) {
    if (checkBalanceTime <= 0) {
      balanceNotEnough = true;
      checkBalanceTime = seconds;
      showBalanceTime = XinDongCalendarUtil.timeTextHMS(checkBalanceTime);
      update();
    }
  }
}
